package com.woorigil.social.domain;

import com.woorigil.social.BaseObject;

public class PageNavigator extends BaseObject {
	private static final int DEFAULT_ITEM_COUNT_IN_PAGE = 18;
	private static final int DEFAULT_PAGE_COUNT_IN_PAGE = 10;
	
	private int itemCountInPage = DEFAULT_PAGE_COUNT_IN_PAGE;
	private int pageCountInPage = DEFAULT_ITEM_COUNT_IN_PAGE;
	private int page;
	private int lastPage;
	private int totalItemCount;
	
	public PageNavigator() {
		itemCountInPage = DEFAULT_ITEM_COUNT_IN_PAGE;
		pageCountInPage = DEFAULT_PAGE_COUNT_IN_PAGE;
	}
	
//	public PageNavigator(int itemsPerPage, int pagesInNavigation, int totalItemCount) {
//		this.itemCountInPage = itemsPerPage;
//		this.pageCountInPage = pagesInNavigation;
//		this.setTotalItemCount(totalItemCount);
//	}

	public int getPage() {
		if (page < 1) {
			page = 1;
		}
		return page;
	}

	public int getRownumFrom() {
		return (getPage() - 1) * itemCountInPage;
	}

	public int getRownumTo() {
		return getPage() * itemCountInPage;
	}
	
	public int getPageFrom() {
		return (getPage() - 1) - ((getPage() - 1) % pageCountInPage) + 1; 
	}
	
	public int getPageTo() {
		int maxByRange = getPageFrom() + (pageCountInPage - 1);
		return (maxByRange <= this.lastPage) ? maxByRange : this.lastPage;
	}

	public void setTotalItemCount(int totalItemCount) {
		this.totalItemCount = totalItemCount;
		this.setLastPage();
	}

	private void setLastPage() {
		this.lastPage = (totalItemCount % itemCountInPage == 0) ? (totalItemCount / itemCountInPage) : (totalItemCount / itemCountInPage) + 1;
	}
	
	public int getPrevPage() {
		if (getPage() > 1) {
			return getPage() - 1;
		} else {
			return getPage();
		}
	}
	
	public int getNextPage() {
		if (getPage() < getLastPage()) {
			return getPage() + 1;
		} else {
			return getPage();
		}
	}

	public int getItemCountInPage() {
		return itemCountInPage;
	}

	public void setItemCountInPage(int itemsPerPage) {
		this.itemCountInPage = itemsPerPage;
	}

	public int getPageCountInPage() {
		return pageCountInPage;
	}

	public void setPageCountInPage(int pagesInNavigation) {
		this.pageCountInPage = pagesInNavigation;
	}

	public int getLastPage() {
		return lastPage;
	}

	public void setLastPage(int lastPage) {
		this.lastPage = lastPage;
	}

	public static int getDefaultItemCountInPage() {
		return DEFAULT_ITEM_COUNT_IN_PAGE;
	}

	public static int getDefaultPageCountInPage() {
		return DEFAULT_PAGE_COUNT_IN_PAGE;
	}

	public int getTotalItemCount() {
		return totalItemCount;
	}

	public void setPage(int page) {
		this.page = page;
	}
}
